'use strict'

//ajax提交公共方法
import axios from 'axios'
import qs from 'qs'
import $ from 'jquery'
import api from './api'

// const loading = this.$loading({
//   lock: true,
//   text: '数据加载中...',
//   spinner: 'el-icon-loading',
//   background: 'rgba(0, 0, 0, 0.7)'
// }),loadingTime = null;

axios.interceptors.request.use(config => {

  // 不是权限认证接口
/* if(config.url.indexOf(api.login) == -1){
      let token =  JSON.parse(sessionStorage.getItem("token"));
      if(token ){
        let currentTime = new Date().getTime();
        let expires = parseInt(sessionStorage.getItem("expires"));
        let access_token = "";
        if(currentTime > expires || expires-currentTime < 100000){
          let data = {
            grant_type:'refresh_token',
            refresh_token:token.refresh_token,
          };
          //jquery AJAX同步请求
          $.ajax({
            url:"/api"+api.login,
            type:'POST', //GET
            async:false, //或false,是否异步
            data:data,
            timeout:20000, //超时时间
            dataType:'json', //返回的数据格式：
            beforeSend:function(xhr){
              xhr.setRequestHeader("Authorization", "Basic " + btoa("my-trusted-client:secret"));
            },
            success:function(data,textStatus,jqXHR){
              if (!data.access_token){
                window.location.href="/";
                sessionStorage.removeItem("token");
                sessionStorage.removeItem("expires");
              }else{
                access_token = data.access_token;
                let expires = new Date().getTime()+data.expires_in*1000;
                sessionStorage.setItem("token",JSON.stringify(data));
                sessionStorage.setItem("expires",expires);
              }
            },
            error:function(xhr,textStatus){
              if (!access_token){
               window.location.href="/";
                sessionStorage.removeItem("token");
                sessionStorage.removeItem("expires");
              }
            },
            complete:function(){
            }
          })
        }else{
          access_token = token.access_token;
        }
        config.headers["Authorization"] = "Bearer "+access_token;
       /!* if(config.data){
          let data = config.data;
          data['access_token'] = access_token;
          config.data = data;
        }else{
          let params = config.params;
          params['access_token'] = access_token;
          config.params = params;
        }*!/

      }else {
        window.location.href="/";
        sessionStorage.removeItem("token");
        sessionStorage.removeItem("expires");
         //return Promise.reject(error)
      }
  }*/
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.resolve(error.response)
})

function requestToken(url,data) {
  return axios({
    method: 'post',
    baseURL: '/api/',
    url,
    data: qs.stringify(data),
    timeout: 20000,
    auth: {
      username: 'my-trusted-client',
      password: 'secret'
    },
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
  }).then(
    (response) => {
      return checkStatus(response)
    }
  ).then(
    (res) => {
      //如果是登录请求，在sessionStorage中放置用户token信息
      if (res.status != -404) {
        if(res.config.url.indexOf(api.login) != -1){
          if(res.data.access_token){
            let expires = new Date().getTime()+res.data.expires_in*1000;
            sessionStorage.setItem("token",JSON.stringify(res.data));
            sessionStorage.setItem("expires",expires);
          }
        }
      }
      return checkCode(res);
    }
  )
}

function checkStatus (response) {
  // 如果http状态码正常，则直接返回数据
  if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
    return response
    // 如果不需要除了data之外的数据，可以直接 return response.data
  }
  // 异常状态下，把错误信息返回去
  return {
    status: -404,
    msg: '网络异常'
  }
}

function checkCode (res) {
  // 如果code异常(这里已经包括网络错误，服务器错误，后端抛出的错误)，可以弹出一个错误提示，告诉用户
  if (res.status === -404) {
    throw new Error(res.msg)
  }
  return res
}

export default {
  login:function(url,data) {
    return requestToken(url,data)
  },
  post:function (url, data) {
    return axios({
      method: 'post',
      url,
      //data: qs.stringify(data),
      data: data,
      timeout: 20000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        //'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  },
  get:function  (url, params) {
    return axios({
      method: 'get',
      url,
      params, // get 请求时带的参数
      timeout: 20000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  },
  patch:function (url,params) {
    return axios.patch(url, params).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  },
  put:function (url,params) {
    return axios.put(url, params).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  },
  delete:function (url,params) {
    return axios.delete(url, {
      data: params
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  }
}
